package com.m3839.sdk.common.base;

import com.m3839.sdk.common.util.LogUtils;

import org.json.JSONObject;

import java.lang.reflect.ParameterizedType;

/**
 * @author ChenBaoyang
 * @description: BaseBean
 * @date 2021/11/27 14:00
 */
public class ResponseBean<T extends BaseBean> {

    /**
     * 返回的参数key
     */
    private static final String KEY_CODE = "code";
    private static final String KEY_MSG = "message";
    private static final String KEY_RESULT = "result";
    private static final String KEY_DATA = "data";

    /**
     * sdk相关接口响应回来的code字段
     */
    private int code;

    /**
     * sdk相关接口响应回来的message字段
     */
    private String message;

    /**
     * 响应的数据内容
     */
    private T data;

    public ResponseBean() {
    }

    private ResponseBean(int code, String message, T data) {
        this.code = code;
        this.message = message;
        this.data = data;
    }

    public void parse(String jsonString){
        parse(jsonString, false);
    }

    public void parse(String jsonString, boolean result) {
        try {
            JSONObject jsonObject = new JSONObject(jsonString);
            code = jsonObject.optInt(KEY_CODE);
            message = jsonObject.optString(KEY_MSG);
            JSONObject dataJson = jsonObject.optJSONObject(result ? KEY_RESULT : KEY_DATA);
            data = getInstanceOfT();
            data = (T) data.parseBean(dataJson);
        } catch (Exception e) {
            LogUtils.flog(e.getMessage());
        }
    }

    private T getInstanceOfT() {
        ParameterizedType superClass = (ParameterizedType) getClass().getGenericSuperclass();
        Class<T> type = (Class<T>) superClass.getActualTypeArguments()[0];
        try {
            return type.newInstance();
        } catch (Exception e) {
            // Oops, no default constructor
            throw new RuntimeException(e);
        }
    }

    public int getCode() {
        return code;
    }

    public String getMessage() {
        return message;
    }

    public T getData() {
        return data;
    }
}
